<!--
 * @Author: 李煌
 * @Date: 2023-04-27 11:47:24
 * @LastEditors: 李煌
 * @LastEditTime: 2023-05-06 09:46:21
 * @Description: 节点编辑器
-->
<template>
  <el-drawer
    :visible.sync="approverDrawer"
    custom-class="set_promoter"
    append-to-body
    direction="rtl"
    :before-close="saveData"
    size="460px"
    :show-close="false"
    :close-on-click-modal="false"
  >
    <template v-if="approverConfig">
      <div slot="title" class="title flex">
        <span v-if="!titleInputFlag">{{ nodeName }}</span>
        <el-input
          maxlength="20"
          autofocus
          v-else
          v-model="nodeName"
          placeholder=""
        ></el-input>
        <!-- 默认条件不需编辑 -->
        <el-button
          v-show="operationType != 'check' && this.approverConfig.type != 0"
          class="el-icon-edit edit_button"
          type="text"
          @click="clickEdit"
        ></el-button>
      </div>

      <div class="rule_node_content">
        <!-- <component
          :is="getFormComponent"
          v-model="approverConfig"
          :defaultApprovalDrawer="defaultApprovalDrawer"
        /> -->
        <baseDetail
          v-if="approverConfig.type === 0"
          ref="baseDetail"
          :strategyBaseFormCopy="
            this.approverConfig && this.approverConfig.nodeDetail
              ? this.approverConfig.nodeDetail
              : {}
          "
        ></baseDetail>
        <div class="content_detail" v-if="approverConfig.type === 2">
          <p>配置内容</p>
          <contentStrategy
            :activityData="ruleForm.activityData"
            @getActivityData="getActivityData"
            v-if="approverConfig.type === 2"
          ></contentStrategy>
          <p>触达方式</p>
          <el-radio-group
            v-model="ruleForm.messageType"
            :disabled="operationType == 'check'"
          >
            <el-radio
              v-for="(item, index) in messageTypeList"
              :key="index"
              :label="item.id"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
          <p>通知模版</p>
          <el-select
            v-model="ruleForm.templateType"
            placeholder="请选择"
            :disabled="operationType == 'check'"
          >
            <el-option
              v-for="(item, index) in templateList"
              :key="index"
              :value="item.templateId"
              :label="item.templateName"
            ></el-option>
          </el-select>
        </div>
        <div v-if="approverConfig.type === 3">
          <el-tag effect="light" class="shunt_set_tips">
            <i class="el-icon-warning"></i
            >用户将按照流量分配比例随机进入任一分支，流量总和为100%</el-tag
          >
          <div class="shunt_content">
            <p class="node_little_title">流量设置</p>
            <el-input-number
              v-model="setNum"
              size="small"
              :min="0"
              :max="100"
              :disabled="operationType == 'check'"
            ></el-input-number>
            <span>剩余可设置流量{{ residueNum }}%</span>
          </div>
        </div>

        <div class="control_detail" v-if="approverConfig.type === 6">
          <p>配置控制条件</p>
          <controlDetail
            :initialOperationalControlList="operationalControlList"
            :approverConfig="approverConfig"
            ref="controlDetail"
            v-if="approverConfig.type === 6 && approverDrawer"
          ></controlDetail>
        </div>
        <div class="strategy_control_content" v-if="approverConfig.type === 1">
          <targetDetail
            ref="targetDetail"
            :initialTargetDetailList="targetDetail"
            :approverConfig="approverConfig"
            v-if="approverConfig.type === 1 && approverDrawer"
          ></targetDetail>
        </div>
      </div>

      <div class="set_promoter_footer flex">
        <!-- 默认条件弹框只展示关闭按钮 -->
        <!-- <div v-if="defaultApprovalDrawer">
          <el-button type="primary" @click="approverDrawer = false"
            >关闭</el-button
          >
        </div> -->
        <div class="flex">
          <el-button type="primary" @click="saveApprover">确定</el-button>
          <el-button @click="approverDrawer = false">取消</el-button>
        </div>
      </div>
    </template>
  </el-drawer>
</template>

<script>
import baseDetail from "../../strategy/index.vue";
import contentStrategy from "./contentStrategy.vue";
import controlDetail from "./controlDetail.vue";
import targetDetail from "./targetDetail.vue";
import { queryMessageConfigList } from "../../../api/strategy/index";

export default {
  inject: ["findNode", "getFlatRoot"],

  components: { baseDetail, contentStrategy, controlDetail, targetDetail },
  computed: {
    // 获取表单组件
    getFormComponent() {
      if (!this.approverConfig) return;
      return this.$factory.getFormComponentName(this.approverConfig.type);
    },
    // 默认条件表单
    defaultApprovalDrawer() {
      return this.approverConfig.nodeName == "默认";
    },
    residueNum() {
      let num = 100;
      this.shuntList.forEach((item, index) => {
        if (this.approverConfig.nodeId != item.nodeId && item.nodeDetail) {
          num = num - Number(item.nodeDetail.num || 0);
        }
      });
      return num;
    },
  },
  data() {
    return {
      approverDrawer: false, //审批弹框
      //审批弹框字段Obj
      approverConfig: {},
      // 处理节点名称更改的标志位
      titleInputFlag: false,
      // 更改的节点名称
      nodeName: "",
      messageTypeList: [
        {
          id: "1",
          label: "短信",
        },
        {
          id: "2",
          label: "邮件",
        },
        {
          id: "3",
          label: "微信公众号",
        },
        {
          id: "4",
          label: "APP",
        },
      ],
      templateList: [
        {
          id: "1",
          label: "模版1",
        },
        {
          id: "2",
          label: "模版2",
        },
      ],
      ruleForm: {
        name: "",
        type: "1",
        messageType: "1",
        templateType: "",
        activityName: "",
        activityData: {},
      },
      contentData: {},
      targetDetailList: [],
      operationalControlList: [],
      branchList: [],
      selectCurrentNode: {},
      nodeType: "",
      shuntList: [],
      setNum: "",
      operationType: "",
    };
  },
  mounted() {
    this.operationType = this.$route.query.type;
  },
  methods: {
    async getTemplateList() {
      queryMessageConfigList({}, 1, 30).then((response) => {
        if (response && response.rows) {
          this.templateList = response.rows.map((item) => {
            return { ...item, id: item.templateId };
          });
        }
      });
    },
    disposeInitialData() {
      //清空数据
      this.ruleForm = {
        name: "",
        type: "1",
        messageType: "1",
        templateType: "",
        activityName: "",
        activityData: {},
      };
      const selectCurrentNode = this.approverConfig.nodeDetail || {};
      //获取分流数据
      let allNodes = this.getFlatRoot();
      if (allNodes) {
        for (let key in allNodes) {
          let item = allNodes[key];
          if (
            item &&
            item.type == 4 &&
            item.nodeId == this.approverConfig.fatherID
          ) {
            this.shuntList = item.conditionNodes || [];
          }
        }
      }
      if (this.approverConfig.type === 2) {
        this.ruleForm = {
          name: selectCurrentNode.name,
          type:
            selectCurrentNode.typeData && selectCurrentNode.typeData.id
              ? selectCurrentNode.typeData.id
              : "1",
          messageType:
            selectCurrentNode.modeAccessData &&
            selectCurrentNode.modeAccessData.id
              ? selectCurrentNode.modeAccessData.id
              : "",
          templateType:
            selectCurrentNode.templateTypeData &&
            selectCurrentNode.templateTypeData.id
              ? selectCurrentNode.templateTypeData.id
              : "",
          activityName: selectCurrentNode.content
            ? selectCurrentNode.content
            : "",
          activityData:
            selectCurrentNode.activityData && selectCurrentNode.activityData.id
              ? selectCurrentNode.activityData
              : {},
        };
      } else if (this.approverConfig.type === 1) {
        this.targetDetail = selectCurrentNode;
      } else if (this.approverConfig.type === 3) {
        this.setNum = selectCurrentNode.num || 0;
      } else if (this.approverConfig.type === 6) {
        this.operationalControlList =
          selectCurrentNode.operationalControlList || [];
      }
    },
    getActivityData(data) {
      console.log("getActivityData  editor  ", data);
      if (data) {
        this.ruleForm.activityData = data;
        this.ruleForm.activityName = data.name;
      }
    },
    // 显示input框 以及校验输入
    clickEdit() {
      this.titleInputFlag = !this.titleInputFlag;
      if (!this.titleInputFlag && this.nodeName == "默认") {
        this.nodeName = this.approverConfig.nodeName;
        this.titleInputFlag = true;
        return this.$message.error("不能取名为默认");
      }
    },
    //审批人抄送人显示和校验
    setApproverStr() {
      return this.$factory.getTypeTextHandle(
        this.approverConfig.type,
        this.approverConfig
      );
    },
    getBeforeSave() {
      return this.$factory.getTypeBeforeSave(
        this.approverConfig.type,
        this.approverConfig
      );
    },
    //保存弹框设置
    saveApprover() {
      this.saveData();
    },
    saveData() {
      this.approverConfig.error = !this.getBeforeSave();
      let node = this.findNode(this.approverConfig.nodeId);
      if (!node) {
        throw Error("无效节点对象");
      }
      for (let kv in this.approverConfig) {
        if (
          [
            "nodeName",
            "nodeId",
            "childNode",
            "type",
            "fatherID",
            "conditionNodes",
            "level",
          ].includes(kv)
        )
          continue;
        node[kv] = this.approverConfig[kv];
      }
      node.nodeName = this.nodeName;
      let data = {};
      if (this.approverConfig.type === 0) {
        let baseDetailData = this.$refs.baseDetail.getForm();
        localStorage.setItem("baseDetailData", JSON.stringify(baseDetailData));
        data = { ...baseDetailData };
      } else if (this.approverConfig.type === 2) {
        data = {
          ...this.ruleForm,
          contentType:
            this.ruleForm.activityData && this.ruleForm.activityData.contentType
              ? this.ruleForm.activityData.contentType
              : "",
          content:
            this.ruleForm.activityData && this.ruleForm.activityData.name
              ? this.ruleForm.activityData.name
              : "",
          modeAccessData: this.getType(
            this.ruleForm.messageType,
            this.messageTypeList
          ),
          templateTypeData: this.getType(
            this.ruleForm.templateType,
            this.templateList
          ),
        };
      } else if (this.approverConfig.type === 1) {
        let targetDetailData = this.$refs.targetDetail.confirm();
        if (targetDetailData) {
          data = { ...targetDetailData };
        }
      } else if (this.approverConfig.type === 3) {
        if (this.setNum > this.residueNum) {
          this.$modal.msgError("可设置最大流量为" + this.residueNum);
          return;
        }
        data = { num: this.setNum };
      } else if (this.approverConfig.type === 6) {
        let controlDetailData = this.$refs.controlDetail.confirm();
        data = {
          ...controlDetailData,
        };
      }
      this.$set(node, "nodeDetail", data);
      this.approverDrawer = false;
    },
    getType(type, list) {
      let currentItem = list.find((item) => {
        return item.id === type;
      });
      return currentItem;
    },
    //打开弹框
    openDrawer(data) {
      if (data.type === 10) {
        return;
      }
      this.approverDrawer = true;
      this.titleInputFlag = false;
      // 默认条件
      if (data.type === 4 || data.type === 5) {
        this.approverConfig = data.conditionNodes[0];
      } else {
        this.approverConfig = JSON.parse(JSON.stringify(data));
      }

      this.nodeName = this.approverConfig.nodeName;
      if (this.approverConfig.type == 2) {
        this.getTemplateList();
      }
      this.disposeInitialData();
    },
  },
};
</script>

<style lang="less" scoped>
.select-avtivity {
  width: 300px;
  .el-input {
    width: 100%;
  }
}
.rule_node_detail {
  background: #fff;
  padding-left: 10px;
}
.rule_form {
  .el-input {
    width: 30%;
    input {
      height: 38px;
    }
  }
  .el-select {
    width: 40%;
  }
}
.el-radio {
  margin-right: 15px;
}
.rule_node_content {
  padding: 0 16px;
}
.content_detail {
  font-size: 14px;

  p {
    margin-bottom: 10px;
  }
  .el-input {
    width: 70%;
  }
}
.strategy_control_content {
  .title {
    color: #606266;
    font-weight: 500;
    margin-bottom: 10px;
  }
  .el-radio-group {
    display: inline-flex;
    flex-direction: column;
    .el-radio {
      display: inline-flex;
      align-items: center;
      margin-top: 10px;
    }
  }
  .strategy_control_item {
    width: 100%;
    span {
      display: inline-block;
      width: 35%;
    }
  }
}
.footer {
  margin-top: 20px;
  // width: 100%;
  // display: flex;
  // justify-content: center;
}
.shunt_set_tips {
  margin-top: 10px;
}
.shunt_content {
  display: flex;
  align-items: center;
  margin-top: 10px;
  font-size: 14px;
  span {
    margin-left: 15px;
  }
  .node_little_title {
    font-weight: 600;
    margin: 5px;
  }
}
</style>
